package com.centit.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyPreFilter;
import com.centit.framework.common.ResponseMapData;
import com.centit.support.database.utils.PageDesc;

public class LayuiResultUtil  {
	  private static Log logger = LogFactory.getLog(LayuiResultUtil.class);
	    private final static String DEFAULT_RESPONSE_CHARACTER = "UTF-8";
	 /**
     * 格式化Json数据输出
     *
     * @param response
     */
	

    public static void layuiwriteResponseDataAsJson(ResponseMapData resData, PageDesc pageDesc, HttpServletResponse response) {
    	 Map<String, Object> param = new HashMap<>();
         param.put(ResponseMapData.RES_CODE_FILED, resData.getCode() );
         param.put("msg",  resData.getMessage());
         param.put("count",  pageDesc.getTotalRows());
         if(resData.getData()!=null)
             param.put(ResponseMapData.RES_DATA_FILED,  resData.getData().get("objList"));
         PropertyPreFilter simplePropertyPreFilter=null;
         String text = JSONObject.toJSONString(param, simplePropertyPreFilter);
         writeOriginalJson(text,response);
    }
    /**
     * 格式化Json数据输出
     *
     * @param response
     */
    public static void writeOriginalJson(String jsonValue, HttpServletResponse response) {
    	writeOriginalResponse("application/json; charset=utf-8",
    			jsonValue,response);
    }
    public static <T> void writeOriginalResponse(String contentType, T objValue,
    		HttpServletResponse response) {
    	//response.setHeader("Cache-Control","no-store");
    	//response.setHeader("Pragma","no-cache");
        response.setCharacterEncoding(DEFAULT_RESPONSE_CHARACTER);
        response.setContentType(contentType);//"application/json; charset=utf-8"); 
        try {
        	if(objValue instanceof String)
        		response.getWriter().write((String)objValue);
        	else
        		response.getWriter().print(objValue);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
